<?php


namespace App\library\services\lib;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class RabbitMQ
{
    private $host;
    private $port;
    private $user;
    private $password;
    protected $connection;
    protected $channel;

    /**
     * RabbitMQ constructor.
     */
    public function __construct()
    {
        $this->host = env('RABBITMQ_HOST', '127.0.0.1');
        $this->port = env('RABBITMQ_PORT', 5672);
        $this->user = env('RABBITMQ_USER', 'guest');
        $this->password = env('RABBITMQ_PASSWORD', 'guest');

        $this->connection = new AMQPStreamConnection($this->host, $this->port, $this->user, $this->password);
        $this->channel    = $this->connection->channel();
    }

    /**
     * Author:Zhongyuan Lu
     * 生成信息
     * @param $message
     * @param $routeKey
     * @param string $exchange
     * @param array $properties
     */
    public function sendMessage($message, $routeKey, $exchange = '', $properties = [])
    {
        $data = new AMQPMessage(
            $message, $properties
        );
        $this->channel->basic_publish($data, $exchange, $routeKey);
    }

    /**
     * Author:Zhongyuan Lu
     * 消费消息
     * @param $queueName
     * @param $callback
     * @throws \ErrorException
     */
    public function consumeMessage($queueName,$callback)
    {
        $this->channel->basic_consume($queueName, '', false, false, false, false, $callback);
        while ($this->channel->is_consuming()) {
            $this->channel->wait();
        }
    }

    /**
     * @throws \Exception
     */
    public function __destruct()
    {
        $this->channel->close();
        $this->connection->close();
    }

}
